package com.bristua.mall.order.biz;

import com.bristua.mall.common.exception.BizException;
import com.bristua.mall.common.utils.*;
import com.bristua.mall.order.dao.TOrderGoodsMapper;
import com.bristua.mall.order.dao.TOrderMapper;
import com.bristua.mall.order.enums.OrderCode;
import com.bristua.mall.order.model.TOrder;
import com.bristua.mall.order.model.TOrderGoods;
import com.bristua.mall.order.model.condition.submitOrder.SubmitOrder;
import com.bristua.mall.order.model.condition.submitOrder.SubmitOrderGoods;
import com.bristua.mall.user.dao.TUserAdressMapper;
import com.bristua.mall.user.model.TUser;
import com.bristua.mall.user.model.TUserAdress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/3/24.
 */
@Service
@Transactional
public class SubmitOrderBiz {

    private static final Logger logger = LoggerFactory.getLogger(SubmitOrderBiz.class);

    @Resource
    private TOrderMapper tOrderMapper;

    @Autowired
    private CacheUtil cacheUtil;

    @Autowired
    private TUserAdressMapper tUserAdressMapper;


    @Autowired
    private DataCenterAPIUrl dataCenterAPIUrl;

    @Resource
    private TOrderGoodsMapper tOrderGoodsMapper;


    @Autowired
    private RestTemplate restTemplate;

    public Map<String,Object> submitOrder(SubmitOrder submitOrder){

        logger.info("==>提交的订单参数:"+JsonUtil.toJson(submitOrder));

        TUser userSession = (TUser) cacheUtil.getUserSession();
        String creatTime = DateUtil.getDateTime3();
        TOrder tOrder = new TOrder();
        tOrder.setOrderId(SequenceUtil.nextId());
        tOrder.setUserId(userSession.getUserId());
        List<SubmitOrderGoods> goods = submitOrder.getGoods();
        int buyNum = 0;
        BigDecimal allPrice = new BigDecimal("0");
        if(goods!=null && goods.size()>0){
            for(SubmitOrderGoods submitOrderGoods : goods){
                TOrderGoods tOrderGoods = new TOrderGoods();
                tOrderGoods.setOrderGoodsId(SequenceUtil.nextId());
                tOrderGoods.setBuyNum(submitOrderGoods.getBuyNum());
                tOrderGoods.setCreateTime(creatTime);
                tOrderGoods.setGoodsId(submitOrderGoods.getGoodsId());
                tOrderGoods.setOrderId(tOrder.getOrderId());
                tOrderGoods.setProductId(submitOrderGoods.getProductId());

                buyNum = buyNum + Integer.valueOf(submitOrderGoods.getBuyNum());
                Map map = queryGoodsById(submitOrderGoods.getGoodsId());

                if(map==null){
                    throw new BizException(OrderCode.GOODS_NOT_EXIST.getCode(),OrderCode.GOODS_NOT_EXIST.getMsg()+",商品ID"+submitOrderGoods.getGoodsId());
                }
                tOrderGoods.setGoodsName(String.valueOf(map.get("name")));
                String price = String.valueOf(map.get("salePrice"));
                BigDecimal multiply = new BigDecimal(price).multiply(new BigDecimal("100"));
                price = String.valueOf(multiply.longValue());
                tOrderGoods.setGoodsPrice(price);
                Object medias = map.get("medias");
                if(medias!=null){
                    List imgList = (List)medias;
                    if(imgList!=null && imgList.size()>0){
                        Object primary = imgList.get(0);
                        if(primary!=null){
                            Map img = (Map) primary;
                            tOrderGoods.setGoodsImgUrl(String.valueOf(img.get("url")));
                        }
                    }

                }
                Object attributes = map.get("attributes");
                StringBuilder specMsg = new StringBuilder();
                if(attributes!=null && attributes instanceof List){
                    List specs = (List)attributes;
                    for(int i=0;i<specs.size();i++){
                        Object o = specs.get(i);
                        if(o!=null){
                            Map skuAttribute = (Map)o;
                            if(i==specs.size()-1){
                                specMsg.append(String.valueOf(skuAttribute.get("option"))).append(":").append(String.valueOf(skuAttribute.get("value")));
                            }else{
                                specMsg.append(String.valueOf(skuAttribute.get("option"))).append(":").append(String.valueOf(skuAttribute.get("value"))).append(" ");
                            }

                        }

                    }
                }
                tOrderGoods.setSpecMsg(specMsg.toString());
                tOrderGoodsMapper.insert(tOrderGoods);
                allPrice = allPrice.add(new BigDecimal(price).multiply(new BigDecimal(submitOrderGoods.getBuyNum())));
            }
        }
        tOrder.setGoodsPrice(String.valueOf(allPrice.longValue()));
        tOrder.setOrderPrice(String.valueOf(allPrice.longValue()));
        tOrder.setBuyNum(String.valueOf(buyNum));
        tOrder.setPayStaus("1");
        tOrder.setFreight("0");
        TUserAdress tUserAdress = tUserAdressMapper.selectByPrimaryKey(submitOrder.getUserAddressId());
        if(tUserAdress==null){
            throw new BizException(OrderCode.USER_TAKE_GOODS_ADDRESS_NOT_EXIST.getCode(),OrderCode.USER_TAKE_GOODS_ADDRESS_NOT_EXIST.getMsg());
        }
        tOrder.setAddressName(tUserAdress.getReceiveAddressName());
        tOrder.setCreateTime(creatTime);
        tOrder.setOrderStatus("1");
        tOrder.setUserName(userSession.getUserName());
        tOrder.setPhone(tUserAdress.getReceivePhone());
        tOrder.setReceiveGoodsName(tUserAdress.getReceiveGoodsName());
        tOrder.setUserAddressId(tUserAdress.getUserAddressId());
        tOrderMapper.insert(tOrder);
        Map<String,Object> data = new HashMap();
        data.put("orderId",tOrder.getOrderId());
        return data;
    }

    public Map queryGoodsById(String goodsId){
        String url = dataCenterAPIUrl.getUrl()+DataCenterAPIUrl.getGoodsUrl;
        url = String.format(url, goodsId);
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
        String body = forEntity.getBody();
        Map map = JsonUtil.json2Map(body);
        String code = String.valueOf(Double.valueOf(String.valueOf(map.get("code"))).intValue());
        if("200".equals(code)){
            Map data = (Map)map.get("data");
            List list = (List) data.get("list");
            Object o = list.get(0);
            if(o!=null){
                Map goods = (Map)o;
                return goods;
            }
        }
        return null;
    }

}
